package com.yeskery.nut.application;

import com.yeskery.nut.core.*;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Nut的HttpServlet处理类
 * @author sprout
 * @version 1.0
 * 2022-08-05 11:17
 */
public class NutHttpServlet implements Servlet {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(NutHttpServlet.class.getName());

    /** Nut应用对象 */
    private final NutApplication nutApplication;

    /** Servlet配置对象 */
    private transient ServletConfig config;

    /** 服务上下文 */
    private final ServerContext serverContext;

    /** 请求分发器 */
    private final Dispatcher dispatcher;

    /** Session管理器 */
    private final SessionManager sessionManager;

    /** 服务请求配置对象 */
    private final ServerRequestConfiguration serverRequestConfiguration;

    /** Nut 服务器 */
    private final NutServer nutServer;

    /**
     * 构建一个Controller请求处理器
     * @param nutApplication Nut应用对象
     * @param serverContext 服务上下文
     * @param dispatcher 请求分发器
     * @param sessionManager 会话管理器
     * @param serverRequestConfiguration 服务请求配置对象
     * @param nutServer Nut服务器对象
     */
    public NutHttpServlet(NutApplication nutApplication, ServerContext serverContext, Dispatcher dispatcher,
                          SessionManager sessionManager, ServerRequestConfiguration serverRequestConfiguration, NutServer nutServer) {
        this.nutApplication = nutApplication;
        this.serverContext = serverContext;
        this.dispatcher = dispatcher;
        this.sessionManager = sessionManager;
        this.serverRequestConfiguration = serverRequestConfiguration;
        this.nutServer = nutServer;
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        config = servletConfig;
    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        try {
            com.yeskery.nut.core.Request nutRequest = new com.yeskery.nut.http.servlet.ServletRequest(serverContext, sessionManager,
                    serverRequestConfiguration, (HttpServletRequest) servletRequest);
            Response nutResponse = new com.yeskery.nut.http.servlet.ServletResponse(nutApplication, (HttpServletResponse) servletResponse);
            //请求执行的方法
            nutServer.process(nutRequest, nutResponse, dispatcher, sessionManager);
        } catch (Exception e) {
            logger.log(Level.WARNING, "An Error Occurred While Closing The Server Socket.", e);
            throw e;
        }
    }

    @Override
    public String getServletInfo() {
        return "";
    }

    @Override
    public void destroy() {
        nutApplication.close();
    }
}
